package com.bycx.wechat.util;

import com.bycx.core.util.StringUtils;
import com.bycx.wechat.constant.WeChatConstant;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by yiqr on 2017/6/12.
 */
public class WeChatHttpUtil {
    private static Log log= LogFactory.getLog(WeChatHttpUtil.class);
    /**
     * http get
     * @param url
     * @return
     */
    public static String get(String url){
        String rs = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet post = new HttpGet(url);
        try {
            CloseableHttpResponse resp = null;
            try {
                resp = httpclient.execute(post);
                StatusLine status = resp.getStatusLine();
                if(status.getStatusCode()==200){
                    HttpEntity entity = resp.getEntity();
                    if(entity!=null){
                        BufferedHttpEntity bufferedEntity = new BufferedHttpEntity(entity);
                        rs = EntityUtils.toString(bufferedEntity, "UTF-8");
                    }
                }
            } catch (Exception e) {
                log.error(e);
            } finally {
                if(resp!=null){
                    resp.close();
                }
            }
        } catch (Exception e) {
            log.error(e);
        }finally{
            try {
                if(httpclient!=null)
                    httpclient.close();
            } catch (Exception e) {
                log.error(e);
            }
        }
        return rs;
    }

    /**
     * http post请求
     * @param url
     * @param jsonData
     * @return
     */
    public static String post(String url,String jsonData){
        String returnValue = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try{
            //第一步：创建HttpClient对象
            httpClient = HttpClients.createDefault();

            //第二步：创建httpPost对象
            HttpPost httpPost = new HttpPost(url);

            //第三步：给httpPost设置JSON格式的参数
            if(StringUtils.isNotEmpty(jsonData)){
                StringEntity requestEntity = new StringEntity(jsonData,"utf-8");
                requestEntity.setContentEncoding("UTF-8");
                httpPost.setHeader("Content-type", "application/json");
                httpPost.setEntity(requestEntity);
            }

            //第四步：发送HttpPost请求，获取返回值
            returnValue = httpClient.execute(httpPost,responseHandler); //调接口获取返回值时，必须用此方法

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return returnValue;
    }
    /**
     * 上传素材
     * @param url 访问的url地址
     * @param file 文件对象（传媒体文件时的参数）
     * @param paramsMap map参数
     * @return
     */
    public static String uploadMedia(String url,File file,Map<String,String> paramsMap) {
        String rsJsonStr="";
        CloseableHttpClient client = null;
        CloseableHttpResponse resp = null;

        try {
            client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            if(file!=null){
                FileBody fb = new FileBody(file);
                //builder.addPart("media", fb);
                Path path = Paths.get(file.getPath());
                builder.addBinaryBody("media", file,
                        ContentType.WILDCARD, file.getName());
            }
            if(paramsMap!=null){
                List<NameValuePair> params=new ArrayList<NameValuePair>();
                for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
                    builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.TEXT_PLAIN.withCharset("UTF-8"));
                }
            }
            HttpEntity entity=builder.build();
            post.setEntity(entity);
            try {
                resp = client.execute(post);
            } catch (IOException e) {
                e.printStackTrace();
            }
            int sc = resp.getStatusLine().getStatusCode();
            if (sc >= 200 && sc < 300) {
                rsJsonStr = EntityUtils.toString(resp.getEntity());
                System.out.println(rsJsonStr);
            }
        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(client!=null) client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(resp!=null) resp.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(rsJsonStr);
        return rsJsonStr;
    }

    public static String uploadNews(String url,String jsonData){
        String returnValue = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try{
            //第一步：创建HttpClient对象
            httpClient = HttpClients.createDefault();

            //第二步：创建httpPost对象
            HttpPost httpPost = new HttpPost(url);

            //第三步：给httpPost设置JSON格式的参数
            StringEntity requestEntity = new StringEntity(jsonData,"utf-8");
            requestEntity.setContentEncoding("UTF-8");
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setEntity(requestEntity);

            //第四步：发送HttpPost请求，获取返回值
            returnValue = httpClient.execute(httpPost,responseHandler); //调接口获取返回值时，必须用此方法

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return returnValue;
    }


    //上传视频素材
    public static String uploadVideoFile(String url, File file ,
                                  String title,String introduction) {
        if(!file.exists()){
            return null;
        }
        String result = null;
        try {
            URL url1 = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Cache-Control", "no-cache");
            String boundary = "-----------------------------"+System.currentTimeMillis();
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);

            OutputStream output = conn.getOutputStream();
            output.write(("--" + boundary + "\r\n").getBytes());
            output.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"\r\n", file.getName()).getBytes());
            output.write("Content-Type: video/mp4 \r\n\r\n".getBytes());
            byte[] data = new byte[1024];
            int len =0;
            FileInputStream input = new FileInputStream(file);
            while((len=input.read(data))>-1){
                output.write(data, 0, len);
            }
            if(StringUtils.isNotEmpty(title)&&StringUtils.isNotEmpty(introduction)){
                output.write(("--" + boundary + "\r\n").getBytes());
                output.write("Content-Disposition: form-data; name=\"description\";\r\n\r\n".getBytes());
                output.write(String.format("{\"title\":\"%s\", \"introduction\":\"%s\"}",title,introduction).getBytes());
            }
            output.write(("\r\n--" + boundary + "--\r\n\r\n").getBytes());
            output.flush();
            output.close();
            input.close();
            InputStream resp = conn.getInputStream();
            StringBuffer sb = new StringBuffer();
            while((len= resp.read(data))>-1)
                sb.append(new String(data,0,len,"utf-8"));
            resp.close();
            result = sb.toString();
            System.out.println(result);
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
        }
        return result;
    }




    /**
     * 获取临时素材
     * @param url
     * @param basePath
     * @param type
     * @return
     */
    public static String downloadTempMedia(String url,String basePath,String type) {
        String filePath="";
        CloseableHttpClient client = null;
        CloseableHttpResponse resp = null;
        try {
            client = HttpClients.createDefault();
            HttpGet get = new HttpGet(url);
            resp = client.execute(get);
            Header headers[] = resp.getAllHeaders();
            int sc = resp.getStatusLine().getStatusCode();
            if(sc>=200&&sc<300) {
                //调用成功
                if(!WeChatConstant.TYPE_MATERIAL_VEDIO.equals(type)){
                    //微信服务器生成的文件名称
                    String file_name ="";
                    for(Header header:headers){
                        if(header.getName().equals("content-disposition")){
                            String content_disposition=header.getValue();
                            String[] content_arr = content_disposition.split(";");
                            if(content_arr.length  == 2){
                                String tmp = content_arr[1];
                                int index = tmp.indexOf("\"");
                                file_name =tmp.substring(index+1, tmp.length()-1);
                            }
                        }
                    }
                    //返回inputstream并存放到本地文件中
                    File file=new File(basePath+File.separator+file_name);
                    InputStream is = resp.getEntity().getContent();
                    System.out.println(resp.toString());
                    FileUtils.copyInputStreamToFile(is, file);
                    filePath=file.getPath();
                    is.close();
                    return filePath;
                }else{
                    //视频格式素材返回json
                    HttpEntity entity = resp.getEntity();
                    if(entity!=null){
                        BufferedHttpEntity bufferedEntity = new BufferedHttpEntity(entity);
                        String rs = EntityUtils.toString(bufferedEntity, "UTF-8");
                        return rs;
                    }
                }
            }
        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(client!=null) client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(resp!=null) resp.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 获取永久素材
     * @param url
     * @param basePath
     * @param type
     * @param mediaId
     * @return
     */
    public static String downloadEverMedia(String url,String basePath,String type,String mediaId) {
        String filePath="";
        CloseableHttpClient client = null;
        CloseableHttpResponse resp = null;
        try {
            client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addTextBody("media_id", mediaId, ContentType.TEXT_PLAIN.withCharset("UTF-8"));
            HttpEntity entity=builder.build();
            post.setEntity(entity);


            resp = client.execute(post);
            Header headers[] = resp.getAllHeaders();
            //微信服务器生成的文件名称

            int sc = resp.getStatusLine().getStatusCode();
            if(sc>=200&&sc<300) {
                if(!WeChatConstant.TYPE_MATERIAL_VEDIO.equals(type)&&!WeChatConstant.TYPE_MATERIAL_NEWS.equals(type)){
                    String file_name ="";
                    for(Header header:headers){
                        if(header.getName().equals("content-disposition")){
                            String content_disposition=header.getValue();
                            String[] content_arr = content_disposition.split(";");
                            if(content_arr.length  == 2){
                                String tmp = content_arr[1];
                                int index = tmp.indexOf("\"");
                                file_name =tmp.substring(index+1, tmp.length()-1);
                            }
                        }
                    }
                    //他类型的素材消息，则响应的直接为素材的内容
                    File file=new File(basePath+File.separator+file_name);
                    InputStream is = resp.getEntity().getContent();
                    System.out.println(resp.toString());
                    FileUtils.copyInputStreamToFile(is, file);
                    is.close();
                    return basePath+File.separator+file_name;
                }else{
                    //视频格式素材和图文素材返回json
                    HttpEntity entity_ = resp.getEntity();
                    if(entity_!=null){
                        BufferedHttpEntity bufferedEntity = new BufferedHttpEntity(entity_);
                        String rs = EntityUtils.toString(bufferedEntity, "UTF-8");
                        return rs;
                    }
                }
            }
        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(client!=null) client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(resp!=null) resp.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 删除素材
     * @param url
     * @param paramsMap
     * @return
     */
    public static String delMedia(String url,Map<String,String> paramsMap) {
        String jsonStr = "";
        CloseableHttpClient client = null;
        CloseableHttpResponse resp = null;

        try {
            client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            if (paramsMap != null) {
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
                    builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.TEXT_PLAIN.withCharset("UTF-8"));
                }
            }
            HttpEntity entity = builder.build();
            post.setEntity(entity);
            try {
                resp = client.execute(post);
            } catch (IOException e) {
                e.printStackTrace();
            }
            int sc = resp.getStatusLine().getStatusCode();
            if (sc >= 200 && sc < 300) {
                jsonStr = EntityUtils.toString(resp.getEntity());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (client != null) client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (resp != null) resp.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonStr;
    }
}
